<?php

namespace mpend\modules\passport\models;

use Yii;
use yii\db\Exception;
use common\base\Model;
use mpend\models\User;

/**
 * 解除绑定手机号模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class UnBindMobileForm extends Model {

    /**
     * @var string 待校验的验证码
     */
    public $user_id;

    /**
     * @var User
     */
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id'], 'required'],
            ['user_id', 'validateUser'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $user = User::findIdentity($this->$attribute);
        if (!$user) {
            return $this->addError($attribute, '未登陆，不能解除绑定!');
        }
        if (!$user->mobile) {
            return $this->addError($attribute, '您还未绑定手机号，无需进行解绑操作');
        }
        $this->_user = $user;
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    protected function getUser() {
        return $this->_user;
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     *
     * @param string $email the target email address
     * @return bool whether the email was sent
     */
    public function unbind() {
        if (!$this->validate()) {
            $this->dumpError();
        }
        return $this->executeTransaction(__FUNCTION__);
    }

    /**
     * 数据保存
     * @inheritdoc
     */
    protected function transactUnbind() {
        $user = $this->getUser();
        if (!$user) {
            $this->dumpError('当前没登陆任何用户');
        }
        $user->removeMobile();
        if (!$user->save()) {
            throw new Exception($user->getErrorMsg());
        }
        return $user;
    }

}
